X

Node.js

Create, Get & Delete Cookies with Express Server

July 24, 2022

/*

Create a Cookie


*/

Install the cookie-parser package with npm. Set the express app to use cookie-parser as middleware. The res.cookie([name of cookie], [value of cookie], [an options object]) method is what will use to create a cookie. It takes three arguments, the name, value & options of the cookie.

For the options object will be using three values. HttpOnly, a boolean when true the browser can't modify the cookie. Javascript can't change the cookie. MaxAge, which is the age in milliseconds of the cookie. Secure, a boolean when true the cookie can only be used by https.

How to create a cookie with the express server

/*

Get A Cookie


*/

To get the value of the cookie, you will use req.cookies.[name of the cookie]. This will return the value you set when you created the cookie.

How to read a cookie with req.cookie.name

/*

Delete A Cookie


*/

To delete a cookie, you will use res.clearCookie([name of cookie], [options object]). The name that you used to create the cookie is the same name you have to enter in to clear the cookie. All the options that you used to create the cookie, except for expires & maxage, will have to be in the options object to clear the cookie.

Using res.clearCookie() to delete a cookie

About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.